﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using COMOSOFT.Class;
using System.Data.SqlClient;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors;
using DevExpress.XtraReports.Configuration;
using DevExpress.XtraReports.UI;
using DevExpress.LookAndFeel;

namespace COMOSOFT.OrderBusiness.Forms
{
    public partial class FrmCostingDetails : Form
    {
        int CMID,CDID;
        string Customer=null,StyleNo;
        DataTable dtbStyleNo,dtbImage,dtbCAM;
        ClassShare cls = new ClassShare("FrmCostingDetails");        
        Report.rptCostingDetails rptCD = null;
        int MAID, MADID,CELID,CSID;
        string Cusname, Group, AddressCus, Phone, AccountName, BankAccount, AddressBank, SwiftCode, Field, Vendor, Remarks;
        bool add = false;
        string sql;
        double EstCons, ActCons, Wastage,Price,Amount;
        List<string> ListItem = new List<string>();
        public FrmCostingDetails(int _CMID)
        {
            InitializeComponent();
            this.CMID = _CMID;
        }
        public void LoadData()
        {
            employeeTableAdapter.Fill(this.dataSetOrderManagement.Employee);
            sp_CustomerListTableAdapter.Fill(dataSetOrderManagement.sp_CustomerList, ClassShare.Usid);
            if (Customer == "")
                txtStyleNo.Enabled = false;         
            if (CMID>0)
            {
                costingMasterTableAdapter.Fill(this.dataSetOrderManagement.CostingMaster,CMID);
                sp_StyleDetailsMATableAdapter.Fill(dataSetOrderManagement.sp_StyleDetailsMA, CMID);
                sp_CostingExtraAmountTableAdapter.Fill(dataSetOrderManagement.sp_CostingExtraAmount, CMID);
                costingExtraLibraryTableAdapter.Fill(this.dataSetOrderManagement.CostingExtraLibrary);
                dtbCAM = cls.GetData("sp_CostAmount", new string[] {"@CMID" }, new object[] {CMID });
                gridControl_CostAmount.DataSource = dtbCAM;
                bandedGridView_CostingMA.ColumnPanelRowHeight = 25;
                if (splitContainerControl_Costing.Enabled == false)
                    splitContainerControl_Costing.Enabled = true;
            }
        }       

        #region[UpdateData]
        public void AddNew()
        {
            costingMasterBindingSource.AddNew();
            txtIssueDate.EditValue = DateTime.Now;
            txtCreator.EditValue =Convert.ToInt64(ClassShare.Usid);
        }
        public void UpdateCost(string com)
        {
            try
            {
                if (com == "Update")
                {
                    costingMasterBindingSource.EndEdit();
                    costingMasterTableAdapter.Update(dataSetOrderManagement.CostingMaster);
                    dataSetOrderManagement.CostingMaster.AcceptChanges();                    
                    CMID = Convert.ToInt32(txtCDID.EditValue);
                    Text = "Style No: " + txtStyleNo.Text;
                }
                else
                {
                    if (MessageBox.Show("Are you sure delete item?", "Delection....", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        dataSetOrderManagement.CostingMaster.Rows[0].Delete();
                        costingMasterTableAdapter.Update(dataSetOrderManagement.CostingMaster);
                        dataSetOrderManagement.CostingMaster.AcceptChanges();
                    }
                }
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[FormLoad]
        private void FrmCostingDetails_Load(object sender, EventArgs e)
        {
            costingExtraLibraryTableAdapter.Fill(dataSetOrderManagement.CostingExtraLibrary);
            this.supplierTableAdapter.Fill(this.dataSetMatarial.Supplier);
            this.sp_CostingSelectMATableAdapter.Fill(this.dataSetOrderManagement.sp_CostingSelectMA);
        }
        #endregion

        #region[Select MA]
        private void repository_SelectMA_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            try
            {
                if (e.CloseMode.ToString() == "Normal")
                {
                    var glk = bandedGridView_CostingMA.ActiveEditor as GridLookUpEdit;
                    var view = glk.Properties.View as GridView;
                    if ((Convert.IsDBNull(view.GetFocusedDataRow()["Price"]) ? "" : view.GetFocusedDataRow()["Price"].ToString()) != "")
                        Price = Convert.ToDouble(view.GetFocusedDataRow()["Price"]);
                    MAID = Convert.ToInt32(view.GetFocusedDataRow()["MAID"]);
                    MADID = Convert.ToInt32(view.GetFocusedDataRow()["MADID"]);
                    if (bandedGridView_CostingMA.IsNewItemRow(bandedGridView_CostingMA.FocusedRowHandle))
                    {
                        string sql = "insert into CostingDetails (MAID,MADID,CMID,SalePrice) " +
                                     " values (@MAID,@MADID,@CMID,@Price)";
                        cls.UpdateDataTypeText(sql, new string[] { "@MAID", "@MADID", "@CMID", "@Price" }, new object[] { MAID, MADID, CMID, Price });
                    }
                    else
                    {
                        CDID = Convert.ToInt32(bandedGridView_CostingMA.GetFocusedDataRow()["CMID"]);
                        string sql2 = "update CostingDetails set MAID=@MAID, MADID=@MADID,SalePrice=@Price,EstCons= @EstCons,ActCons=@ActCons,Wastage=@Wastage where CDID=@CDID ";
                        cls.UpdateDataTypeText(sql2, new string[] { "@MAID", "@MADID", "@Price", "@CDID", "@EstCons", "@ActCons", "@Wastage", }, new object[] { MAID, MADID, Price, CDID,0,0,0 });
                    }
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void repositorySelectMA_ColumnFilterChanged(object sender, EventArgs e)
        {
            var glk = bandedGridView_CostingMA.ActiveEditor as GridLookUpEdit;
            var view = glk.Properties.View as GridView;
            view.OptionsBehavior.AutoExpandAllGroups = true;
        }
        #endregion

        #region[Choose Cus and Style]
        private void txtstlyeCus_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                Customer = txtstlyeCus.EditValue.ToString();
                if (Customer != null && Customer != "")
                {                   
                   LoadStyle();              
                }
                txtStyleNo.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadStyle()
        {
            string sql = "select StyleNo,StyleNo+'-'+StyleName as StyleName " +
                                "from OrderStyleLists " +
                                "where Customer like @Cus ";
                    dtbStyleNo = cls.GetDataSql(sql, new string[] {"@Cus" }, new object[] {Customer});
                    txtStyleNo.Properties.DataSource = dtbStyleNo;
                    txtStyleNo.Properties.DisplayMember = "StyleName";
                    txtStyleNo.Properties.ValueMember = "StyleNo";   
        }

        private void txtStyleNo_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                StyleNo = txtStyleNo.EditValue.ToString();
                if (Customer != null && Customer != "")
                {
                    //string sql = "select OID,PO+'-'+Color as PO " +
                    //             " from MasterPO left join OrderDetails on MasterPO.MPOID=OrderDetails.MPOID " +
                    //            " where MasterPO.Customer like @Cus and StyleNo like @Style " +
                    //            " order by PORCVD DESC";
                    //dtbPO = cls.GetDataSql(sql, new string[] { "@Cus", "@Style" }, new object[] { Customer, StyleNo });
                    //txtPO.Properties.DataSource = dtbPO;
                    //txtPO.Properties.DisplayMember = "PO";
                    //txtPO.Properties.ValueMember = "OID";

                    string sql2 = "select [Image] " +
                                " from OrderStyleLists " +
                                " where Customer like @Cus and StyleNo like @Style ";
                    dtbImage = cls.GetDataSql(sql2, new string[] { "@Cus", "@Style" }, new object[] { Customer, StyleNo });
                    if (dtbImage.Rows[0]["Image"] != null)
                    {
                        txtPicture.EditValue = dtbImage.Rows[0]["Image"];
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[UpadeCostingDetails]
        private void bandedGridView_CostingMA_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                GridView view = bandedGridView_CostingMA as GridView;
                CDID =Convert.ToInt32(view.GetFocusedDataRow()["CDID"]);                
                if ((Convert.IsDBNull(view.GetFocusedDataRow()["EstCons"]) ? "" :view.GetFocusedDataRow()["EstCons"].ToString()) != "")
                     EstCons = Convert.ToDouble(view.GetFocusedDataRow()["EstCons"]);                
                if ((Convert.IsDBNull(view.GetFocusedDataRow()["Wastage"]) ? "" : view.GetFocusedDataRow()["Wastage"].ToString()) != "")
                     Wastage = Convert.ToDouble(view.GetFocusedDataRow()["Wastage"]);
                if ((Convert.IsDBNull(view.GetFocusedDataRow()["Price"]) ? "" : view.GetFocusedDataRow()["Price"].ToString()) != "")
                    Price = Convert.ToDouble(view.GetFocusedDataRow()["Price"]);
                if(!Convert.IsDBNull(view.GetFocusedDataRow()["EstCons"]) && !Convert.IsDBNull(view.GetFocusedDataRow()["Wastage"]))
                {
                    ActCons = EstCons * (1 + (Wastage / 100));
                }                
                cls.UpdateData("sp_CostingDetailsUpdate", new string[] { "@CDID", "@EstCons", "@ActCons", "@Wastage", "@Price" }, new object[] { CDID, EstCons, ActCons, Wastage, Price });
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[ExtraAmount]
        private void repositoryItemGrid_ExtraLib_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            try
            {
                if (e.CloseMode.ToString() == "Normal")
                {
                    var glk = gridExtraAmounts.ActiveEditor as GridLookUpEdit;
                    var view = glk.Properties.View as GridView;
                    CELID = Convert.ToInt32(view.GetFocusedDataRow()["CELID"]);
                    if (gridExtraAmounts.IsNewItemRow(gridExtraAmounts.FocusedRowHandle))
                    {
                        string sql = "insert into CostingSummary (CMID,CELID) " +
                                    " values (@CMID,@CELID)";

                        cls.UpdateDataTypeText(sql, new string[] { "@CMID","@CELID" }, new object[] { CMID,CELID });
                        LoadData();
                    }                    
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void gridExtraAmounts_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                GridView view = gridExtraAmounts as GridView;
                if (!view.IsNewItemRow(e.RowHandle))
                {
                    if ((Convert.IsDBNull(view.GetFocusedDataRow()["Amount"]) ? "" : view.GetFocusedDataRow()["Amount"].ToString()) != "")
                        Amount = Convert.ToDouble(view.GetFocusedDataRow()["Amount"]);
                    CSID = Convert.ToInt32(view.GetFocusedDataRow()["CSID"]);
                    CELID = Convert.ToInt32(view.GetFocusedDataRow()["CELID"]);
                    string sql2 = "update CostingSummary set CELID=@CELID, Amount=@Amount where CSID=@CSID ";
                    cls.UpdateDataTypeText(sql2, new string[] { "@CELID", "@Amount", "@CSID" }, new object[] { CELID, Amount, CSID });
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        #endregion

        #region[EventCosting]
        private void deleteItemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure delete item?", "Deletion...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    GridView view = bandedGridView_CostingMA as GridView;
                    CDID = Convert.ToInt32(view.GetFocusedDataRow()["CDID"]);
                    string sql = "delete from CostingDetails where CDID=@CDID";
                    cls.UpdateDataTypeText(sql, new string[] { "@CDID" }, new object[] { CDID });
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        private void previewToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
        #endregion

        #region[Delete ExtraCost]
        private void deleteItemToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure delete item?", "Deletion...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                GridView view = gridExtraAmounts as GridView;
                CSID = Convert.ToInt32(view.GetFocusedDataRow()["CSID"]);
                string sql = "delete from CostingSummary where CSID=@CSID";
                cls.UpdateDataTypeText(sql, new string[] { "@CSID" }, new object[] { CSID });
                LoadData();
            }
        }
        #endregion       

        #region[Preview]
        public void Preview()
        {
            //ListItem.Clear();
            //ListItem.Add(txtstlyeCus.EditValue.ToString());
            //ListItem.Add(txtStyleNo.EditValue.ToString());
            ////ListItem.Add(txtPO.EditValue.ToString());
            //ListItem.Add(txtIssueDate.EditValue.ToString());
            //ListItem.Add(txt_Type.EditValue.ToString());
            //ListItem.Add(txt_Profit.EditValue.ToString());
            //ListItem.Add(txtCreator.Text.ToString());
            //ListItem.Add(txtstyleRemarks.EditValue.ToString());

            //dtb1 = dataSetOrderManagement.sp_CostingExtraAmount;
            //dtb2 = dtbCAM;
            //frmPvCD = new frmPreviewCostingDetails(bandedGridView_CostingMA, dtb1, dtb2, ListItem);
            //frmPvCD.LoadData();
            //frmPvCD.Show();

            rptCD = new Report.rptCostingDetails(CMID);
            ReportPrintTool printTool = new ReportPrintTool(rptCD);
            printTool.ShowRibbonPreview(UserLookAndFeel.Default);
            
            
        }
        #endregion       

        private void txtstlyeCus_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Tag.ToString() == "Add")
            {                
                dockPanel_AddCus.Show();
            }
        }

        #region[Customer List]
        private void HideButton(bool val1, bool val2)
        {
            dataNavigator_Customer.Buttons.CustomButtons[2].Enabled = val1;
            dataNavigator_Customer.Buttons.CustomButtons[0].Enabled = val2;
            dataNavigator_Customer.Buttons.CustomButtons[3].Enabled = val2;
            groupControl_CustomerList.Enabled = val2;
        }

        private void dataNavigator_Customer_ButtonClick(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.Tag.ToString())
            {
                case "Add":
                    HideButton(true, false);
                    txt_CustomerName.Properties.ReadOnly = false;
                    txt_CustomerName.Focus();
                    txt_CustomerName.Text = "";
                    txt_Group.Text = "";
                    txt_Address.Text = "";
                    txt_Phone.Text = "";
                    txt_AccountName.Text = "";
                    txt_BankAccount.Text = "";
                    txt_BankAddress.Text = "";
                    txt_SwiftCode.Text = "";
                    txt_Feild.Text = "";
                    txt_Vendor.Text = "";
                    txt_Remarks.Text = "";
                    add = true;
                    break;
                case "Save":
                    try
                    {
                        Cusname = txt_CustomerName.Text;
                        Group = txt_Group.Text;
                        AddressCus = txt_Address.Text;
                        Phone = txt_Phone.Text;
                        AccountName = txt_AccountName.Text;
                        BankAccount = txt_BankAccount.Text;
                        AddressBank = txt_BankAddress.Text;
                        SwiftCode = txt_SwiftCode.Text;
                        Field = txt_Feild.Text;
                        Vendor = txt_Vendor.Text;
                        Remarks = txt_Remarks.Text;
                        if (add == false)
                        {
                            sql = "sp_CustomerUpdate";
                        }
                        else
                        {
                            sql = "sp_CustomerInsert";
                        }
                        cls.UpdateData(sql, new string[] { "@Customer", "@Group", "@AddressCus", "@Phone", "@AccountName", "@BankAccount", "@AddressBank", "@SwiftCode", "@Field", "@Vendor", "@Remarks", "@EID" },
                                          new object[] { Cusname, Group, AddressCus, Phone, AccountName, BankAccount, AddressBank, SwiftCode, Field, Vendor, Remarks, ClassShare.Usid });
                        sp_CustomerListTableAdapter.Fill(dataSetOrderManagement.sp_CustomerList, ClassShare.Usid);
                        HideButton(false, true);
                        txt_CustomerName.Properties.ReadOnly = true;
                        add = false;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }

                    break;
                case "Cancel":
                    HideButton(false, true);
                    gridView_CustomerList.FocusedRowHandle = 0;
                    txt_CustomerName.Properties.ReadOnly = true;
                    break;
                case "Refresh":
                    sp_CustomerListTableAdapter.Fill(dataSetOrderManagement.sp_CustomerList, ClassShare.Usid);
                    break;
                case "Exit":
                    dockPanel_AddCus.Hide();
                    break;
            }
        }


        private void gridView_CustomerList_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                txt_CustomerName.Text = view.GetFocusedDataRow()["Customer"].ToString();
                txt_Group.Text = view.GetFocusedDataRow()["Group"].ToString();
                txt_Address.Text = view.GetFocusedDataRow()["AddressCus"].ToString();
                txt_Phone.Text = view.GetFocusedDataRow()["Phone"].ToString();
                txt_AccountName.Text = view.GetFocusedDataRow()["AccountName"].ToString();
                txt_BankAccount.Text = view.GetFocusedDataRow()["BankAccount"].ToString();
                txt_BankAddress.Text = view.GetFocusedDataRow()["AddressBank"].ToString();
                txt_SwiftCode.Text = view.GetFocusedDataRow()["SwiftCode"].ToString();
                txt_Feild.Text = view.GetFocusedDataRow()["Field"].ToString();
                txt_Vendor.Text = view.GetFocusedDataRow()["Vendor"].ToString();
                txt_Remarks.Text = view.GetFocusedDataRow()["Remarks"].ToString();
            }
            catch
            {
            }
        }
        #endregion

        #region[Style Update]
        private void gridView_Style_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            gridView_Style.SetFocusedRowCellValue("Customer", Customer);
            gridView_Style.SetFocusedRowCellValue("Creater", Convert.ToInt64(ClassShare.Usid));
            gridView_Style.SetFocusedRowCellValue("IssueDate", DateTime.Now);
        }

        private void gridView_Style_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                int USID = Convert.ToInt32(view.GetFocusedDataRow()["Creater"]);
                if (ClassShare.Usid == USID)
                {
                    orderStyleListsBindingSource.EndEdit();
                    orderStyleListsTableAdapter.Update(dataSetOrderManagement.OrderStyleLists);
                    dataSetOrderManagement.OrderStyleLists.AcceptChanges();
                    orderStyleListsTableAdapter.Fill(dataSetOrderManagement.OrderStyleLists, Customer);
                }
                else
                {
                    MessageBox.Show("You don't permission!", "Can't update....", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void repositoryItemPopupContainerEdit_Style_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            dockPanel_AddStyle.Show();
            orderStyleListsTableAdapter.Fill(dataSetOrderManagement.OrderStyleLists, Customer);
        }
        #endregion

        private void txtStyleNo_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Tag.ToString() == "Add")
            {
                dockPanel_AddStyle.Show();   
                LoadStyle();
            }
        }

        private void dockPanel_AddStyle_ClosedPanel(object sender, DevExpress.XtraBars.Docking.DockPanelEventArgs e)
        {
            LoadStyle();
        }

        #region[Refresh]
        public void RefreshMA()
        {
            sp_CostingSelectMATableAdapter.Fill(dataSetOrderManagement.sp_CostingSelectMA);
        }
        #endregion

        private void bandedGridView_CostingMA_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                GridView view = bandedGridView_CostingMA as GridView;
                if (e.Column.FieldName == "Wastage")
                {
                    if ((Convert.IsDBNull(view.GetFocusedDataRow()["EstCons"]) ? "" : view.GetFocusedDataRow()["EstCons"].ToString()) != "")
                        EstCons = Convert.ToDouble(view.GetFocusedDataRow()["EstCons"]);
                    if ((Convert.IsDBNull(view.GetFocusedDataRow()["Wastage"]) ? "" : view.GetFocusedDataRow()["Wastage"].ToString()) != "")
                        Wastage = Convert.ToDouble(view.GetFocusedDataRow()["Wastage"]);
                    if (!Convert.IsDBNull(view.GetFocusedDataRow()["EstCons"]) && !Convert.IsDBNull(view.GetFocusedDataRow()["Wastage"]))
                    {
                        ActCons = EstCons * (1 + (Wastage / 100));
                    }
                    view.SetFocusedRowCellValue("ActCons", ActCons);
                }
                if (e.Column.FieldName == "Price")
                {
                    if ((Convert.IsDBNull(view.GetFocusedDataRow()["Price"]) ? "" : view.GetFocusedDataRow()["Price"].ToString()) != "")
                        Price = Convert.ToDouble(view.GetFocusedDataRow()["Price"]);
                    view.SetFocusedRowCellValue("Amount", Price*ActCons);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
